//
//  LGUploadFilesController.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2024/12/27.
//  上传报告文件

#import "LGUploadFilesController.h"
#import <MobileCoreServices/MobileCoreServices.h> // 导入框架
#import "LGUploadFilesCell.h"
@interface LGUploadFilesController ()<UITableViewDelegate,UITableViewDataSource,UIDocumentPickerDelegate,LGUploadFilesCellDelegate,UIAdaptivePresentationControllerDelegate>
/**   */
@property (nonatomic , strong)UITableView *tableView;
/**   */
@property (nonatomic , strong)NSMutableArray *dataArray;
/**   */
@property (nonatomic , copy)NSString *pageNo;

@end

@implementation LGUploadFilesController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"报告上传";
    [self.view addSubview:self.tableView];
    [self emptyViewWithSuperView:self.view frame:self.tableView.frame];
    UIButton *button = [UIButton buttonWithTitle:@"报告上传" topMargin:kMaxY(self.tableView.frame)+viewPix(5)];
    [button addTarget:self action:@selector(uploadReportAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    [self requestData];
}

-(void)requestData{
    self.pageNo = @"1";
    self.dataArray = [NSMutableArray array];
    [self requestMoreData];
}

-(void)requestMoreData{
    [RequestUtil withPOST:@"/doctor/patient.medical_report/pagedList" parameters:@{@"pageNo":self.pageNo,@"pageSize":@"20"} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        self.isfirst = NO;
        [self.emptyView stopBufferAction];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if(code == 200){
            NSArray *tempArray = returnData[@"data"];
            if(tempArray.count>0){
                self.pageNo = [NSString stringWithFormat:@"%ld",[returnData[@"current_page"] integerValue]+1];
                [self.dataArray addObjectsFromArray:tempArray];
            }else{
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        }
        [self.tableView reloadData];
        if(self.dataArray.count == 0){
            [self.emptyView showViewWithImage:@"emptyView2" content:@"暂无上传记录" offset:0];
        }
    } error:^(NSError *error) {
        self.isfirst = NO;
        [self.emptyView stopBufferAction];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if(self.dataArray.count == 0){
            [self.emptyView showViewWithImage:@"emptyView2" content:@"暂无上传记录" offset:0];
        }
    }];
}

//上传文件
-(void)uploadFileAction:(NSURL *)fileUrl{
    NSString *string = [[fileUrl absoluteString] stringByRemovingPercentEncoding];
    NSString *modeName = [[string componentsSeparatedByString:@"/"] lastObject];
    NSLog(@">>fileUrl>>>%@",string);
    if (modeName.length>0) {
        [RequestUtil uploadFile:@"/doctor/upload/reportFile" parameters:@{} withSign:YES fileName:modeName fileArray:@[fileUrl] success:^(NSInteger code, NSString *message, id returnData) {
            if (code == 200) {
                [self requestData];
            }else{
                [TooltipView showMessage:message offset:0];
            }
        } failure:^(NSError *error) {
            [TooltipView showMessage:@"上传失败，请重试" offset:0];
        }];
    }else{
        [TooltipView showMessage:@"文件获取失败" offset:0];
    }
}

-(void)deleteFileAction:(NSString *)fileid{
    __weak typeof(self) weakSelf = self;
    __block NSString *ids = fileid;
    [LGAlertTool alertWithTitle:@"删除报告" content:@"确定要删除这份报告吗？" sureAction:^{
        [RequestUtil withPOST:@"/doctor/patient.medical_report/delete" parameters:@{@"ids":ids} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
            if (code == 200) {
                [weakSelf requestData];
            }else{
                [TooltipView showMessage:message offset:0];
            }
        } error:^(NSError *error) {
            [TooltipView showMessage:@"删除失败，请重试" offset:0];
        }];
    }];
}

-(void)uploadReportAction{
    __weak typeof(self) weakSelf = self;
    [LGAlertTool alertWithTitle:@"选择文件" content:@"1、上传报告需要把每个患者的报告图片打包成待料压缩包再发，手机打包操作步骤已录制做成视\n\n2、拍摄患者报告的时候需要自己先检查一下图片清晰度和报告数量以及拍照规范，不能歪斜，不能反光，不能缺少信息\n\n3、拍摄时手机垂直平行于电脑屏幕拍摄\n\n4、患者报告上传所需要的内容：出院小结、出院记录、手术记承、检验检查\n\n5、打包的文件夹命名以姓名+病种+出院日期及入院日期（例：小红PCI患者2024.12.05入院2024.12.10出院-例：小蓝房频患者2024.11.16入院2024.11.24出院）\n\n6、报告上传需消耗大量流量，请在手机有wif环境下上传报告" sureTitle:@"确认上传" sureAction:^{
        //创建文件选择器，支持选择多种文件类型（如：文本、图片、PDF）
        NSArray *documentTypes = @[(NSString *)kUTTypeArchive,(NSString *)kUTTypeDiskImage];
        UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:documentTypes inMode:UIDocumentPickerModeOpen];
        documentPicker.delegate = weakSelf; // 设置代理
        if (@available(iOS 13.0, *)) {
            documentPicker.shouldShowFileExtensions = YES;
        }
        documentPicker.modalPresentationStyle = UIModalPresentationFullScreen; // 弹出样式
        documentPicker.presentationController.delegate = self;
        [weakSelf presentViewController:documentPicker animated:YES completion:nil]; // 显示文件选择器
    }];
}

//强制全屏
-(UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller traitCollection:(UITraitCollection *)traitCollection{
    return UIModalPresentationFullScreen;
}

// 处理用户选择的文件的URL
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
    [self uploadFileAction:[urls firstObject]];
}

// 取消文件选择时的回调
- (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller {
    NSLog(@"用户取消了文件选择");
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LGUploadFilesCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.dataDic = self.dataArray[indexPath.row];
    cell.delegate = self;
    return cell;
}

-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H-topBarHeight-viewPix(65)-bottomSafeBarHeight/4.0) style:UITableViewStyleGrouped];
        [_tableView registerClass:[LGUploadFilesCell class] forCellReuseIdentifier:@"cell"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, 0.01)];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(requestMoreData)];
    }
    return _tableView;
}



@end
